package com.shanghaionstar.mro.presenter;

import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.framework.mvp.base.IMVPScheduler;
import com.onstar.cn.framework.mvp.base.IMVPView;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.mag.enumtype.RemoteCommandsType;
import com.onstar.cn.map.common.PoiItemInfo;
import com.onstar.cn.rxconstants.RxConstants;
import com.shanghaionstar.mro.iview.IMroPoiView;
import com.shanghaionstar.nav.model.NavInfoModel;
import com.shanghaionstar.nav.model.PoiHistoryInfo;
import com.shanghaionstar.nav.service.NavService;
import com.shanghaionstar.remote.manager.RemoteOperateValidateHelper;
import com.shanghaionstar.remote.model.RemoteModel;
import com.shanghaionstar.sqlite.SearchHistoryImpl;
import com.shanghaionstar.sqlite.TBTHistoryImpl;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.NavHolder;

import rx.functions.Action1;

/**
 * Created by Rengui Lu on 2016/8/23.
 */
public class MroPoiPresenter extends BasePresenter{
    private IMroPoiView mMroView;
    private BaseActivity context;
    private NavService navService;

    public MroPoiPresenter(IMVPScheduler mvpScheduler) {
        super(mvpScheduler);
    }

    @Override
    public void setView(IMVPView view) {
        super.setView(view);
        mMroView = (IMroPoiView) view;
        context = (BaseActivity) view.onActivity();
        navService = new NavService(context);
        helper = new RemoteOperateValidateHelper(context);
    }

    RemoteOperateValidateHelper helper;

    public void saveHis(RemoteModel remoteModel){
        if (remoteModel.getRemoteCommandsType() == RemoteCommandsType.COMMANDS_NAV_DESTINATION ||
                remoteModel.getRemoteCommandsType() == RemoteCommandsType.COMMANDS_TBT_ROUTE) {
            helper.saveHistoryToSql(remoteModel.requestId, remoteModel.poiItemInfo, null, true);
            //将下发历史保存到历史记录中
            helper.saveSearchHistory(remoteModel.poiItemInfo);
        }
        if (mMroView != null) {
            mMroView.showCommandLoading(true);
        }
    }

    /**
     * @param
     * @return void
     * @Title: saveSearchHistory
     * @Description: 保存到历史记录中
     */
    public void saveSearchHistory(PoiItemInfo poiItemInfo) {
        SearchHistoryImpl impl = new SearchHistoryImpl(context);
        impl.saveSearchHistory(poiItemInfo);
        RxBus.getDefault().post(RxConstants.ALL_PAGE_REFRESH, RxConstants.NAV_SAVE_POI);
    }

    public void saveHistoryToSql(String requestId, PoiItemInfo poiItemInfo, String status, boolean isSave) {
        PoiHistoryInfo historyInfo = new PoiHistoryInfo();
        historyInfo.setPoiItemInfo(poiItemInfo);
        if (isSave) {
            historyInfo.setStatus("inProgress");
        } else {
            historyInfo.setStatus(status);
        }
        TBTHistoryImpl impl = new TBTHistoryImpl(context);
        impl.saveOrUpdateModelDestinationHistory(requestId, historyInfo, isSave);
    }


    private void doNavCommand(final NavInfoModel navInfoModel) {
        subscription = navService.doNavCommand(navInfoModel)
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String requestId) {
                        if (navInfoModel.remoteCommandsType == RemoteCommandsType.COMMANDS_NAV_DESTINATION || navInfoModel.remoteCommandsType == RemoteCommandsType.COMMANDS_TBT_ROUTE) {
                            saveHistoryToSql(requestId, navInfoModel.poiItemInfo, null, true);
                            //将下发历史保存到历史记录中
                            saveSearchHistory(navInfoModel.poiItemInfo);
                        }
                        if (mMroView != null) {
                            mMroView.showCommandLoading(true);
                        }
                        NavHolder.getInstance(context).setCurrentSendPoi(navInfoModel.poiItemInfo);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //里面抛出的Error信息
                        if (mMroView != null) {
                            mMroView.onResponseError((OnStarException) throwable);
                            if (ApplicationUtil.isActivityFront()) {
                                mMroView.showAppFrontNavCommandFailToast(NavHolder.getInstance(context).getCurrentSendPoi());
                            } else {
                                mMroView.showAppBackNavCommandFailToast(NavHolder.getInstance(context).getCurrentSendPoi());
                            }
                        }
                    }
                });
    }

    public void sendTbtOrOdd(PoiItemInfo poiItemInfo) {
        helper.sendTbtOrOdd(poiItemInfo);
//        RemoteOperateValidateHelper helper = new RemoteOperateValidateHelper(context);
//        RemoteModel model = helper.getRemoteModel();
//        model.poiItemInfo = poiItemInfo;
//        RemoteOperateManager.getInstance().init(context).exeRemote(model.getRemoteCommandsType());


//        if(ApplicationUtil.getInstance().isCommanding){
//            ApplicationUtil.getInstance().controlCommand(context);
//            return;
//        }else {
//            ApplicationUtil.getInstance().isCommanding = true;
//        }
//        NavInfoModel navInfoModel = new NavInfoModel();
//        if (BusinessUtil.isServiceFeature(FeatureEnum.SENDNAVDESTINATION.value(), context)) {
//            if (PreferencesUtls.getInstance(context).getBoolean(FinalConstants.SharedPreferencesConfig.TBT_CHOOSE_SAVE, true)) {
//                navInfoModel.remoteCommandsType = RemoteCommandsType.COMMANDS_TBT_ROUTE;
//            } else if (PreferencesUtls.getInstance(context).getBoolean(FinalConstants.SharedPreferencesConfig.ODD_CHOOSE_SAVE, false)) {
//                navInfoModel.remoteCommandsType = RemoteCommandsType.COMMANDS_NAV_DESTINATION;
//            }
//        } else {
//            navInfoModel.remoteCommandsType = RemoteCommandsType.COMMANDS_TBT_ROUTE;
//        }
//        navInfoModel.poiItemInfo = poiItemInfo;
//        if (validateTbtOrOdd(poiItemInfo, navInfoModel.remoteCommandsType)) {
//            doNavCommand(navInfoModel);
//        }
    }

//    private boolean validateTbtOrOdd(PoiItemInfo poiItemInfo, RemoteCommandsType remoteCommandsType) {
//        if (poiItemInfo == null) return false;
//        if (remoteCommandsType != RemoteCommandsType.COMMANDS_TBT_ROUTE && remoteCommandsType != RemoteCommandsType.COMMANDS_NAV_DESTINATION)
//            return false;
//        if (!ApplicationUtil.getInstance().isLogin())
//            return false;
////        if (ApplicationUtil.getInstance().isAutoLogings()) {
////            if (mMroView!= null) {
////                mMroView.onResponseError(new OnStarException("", context.getString(R.string.loading)));
////            }
////        }
//        if (!BusinessUtil.checkDriverOrProxyAndShowDialog(context)) {
//            return false;
//        }
//        if (!BusinessUtil.checkPackageRight(Constants.ENTITLEMENT_M05NAVIGATION, context, true)) {
//            return false;
//        }
//        //判断是否正在执行车辆的相关操作
//        if (BusinessUtil.checkInProgressCommand(context, null, false)) {
//            AlertDialogUtil.showAlertDialog(context, context.getString(R.string.dialog_warning),
//                    context.getString(R.string.service_inProcess_alert));
////            BusinessUtil.updateConfigValue(FinalConfigParams.SHARE_DESTINATION, "-1", context);
//            return false;
//        }
//        return true;
//    }
}
